package com.learning.springmvc.base.controllers.controller;


import com.learning.springmvc.base.controllers.bean.User;
import com.learning.springmvc.base.controllers.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName: UserGetController
 * Description: 参数获取
 * <p>
 * https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/htmlsingle/#mvc
 * Date: 2016/12/22 21:00
 *
 * @author SAM SHO
 * @version V1.0
 */
@Controller
@RequestMapping(value = "user")
public class UserGetController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * HttpServletRequest 获取
     * <p>
     * http://localhost:8080/user/getParam?name=sam
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getParam")
    public String getParam(HttpServletRequest request, ModelMap modelMap) {
        String name = request.getParameter("name");
        name = httpServletRequest.getParameter("name");
        User user = userService.get(name);
        modelMap.addAttribute("user", user);
        return "user";
    }

    @RequestMapping(value = "/getParam/session")
    public String getParam(HttpSession session) {
        session.setAttribute("sessionId", "123456");
        return "user";
    }


    @RequestMapping(value = "/getIO")
    public void getIO(OutputStream os) throws IOException {
        // 读取类路径下的图片文件
        ClassPathResource resource = new ClassPathResource("/image.jpg");
        // 将图片写到输出流中
        FileCopyUtils.copy(resource.getInputStream(), os);
    }



    /**
     * 直接参数获取
     * <p>
     * http://localhost:8080/user/getName?name=sam
     *
     * @param name
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getName")
    public String getName(String name, ModelMap modelMap) {
        System.out.println(name);
        User user = userService.get(name);
        modelMap.addAttribute("user", user);
        return "user";
    }

    /**
     * 参数标注 @RequestParam 注解
     * <p>
     * http://localhost:8080/user/getNameAnnotation
     *
     * @param name
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getNameAnnotation")
    public String getNameAnnotation(@RequestParam(value = "name", required = false, defaultValue = "eason") String name, ModelMap modelMap) {
        User user = userService.get(name);
        modelMap.addAttribute("user", user);
        return "user";
    }

    /**
     * 直接对象接收（时间会有问题，需要 InitBinder 支持）
     * <p>
     * http://localhost:8080/user/getObject?name=sam&birthday=2018-09-23
     *
     * @param user
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getObject")
    public String getObject(User user, ModelMap modelMap) {
        System.out.println(user);
        user = userService.get(user.getName());
        modelMap.addAttribute("user", user);
        return "user";
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @InitBinder
    protected void initBinder2(WebDataBinder binder) {
        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }

    /**
     * 访问视图
     * <p>
     * http://localhost:8080/user/form
     *
     * @return
     */
    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String form() {
        return "user_form";
    }

    /**
     * Form 表单提交
     *
     * @param user
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String form(User user, ModelMap modelMap) {
        System.out.println(user);
        user = userService.get(user.getName());
        modelMap.addAttribute("user", user);
        return "user";
    }

    /**
     * URI Template Patterns
     * <p>
     * http://localhost:8080/user/getURITemplate/sam
     * <p>
     * 还支持正则表达式： @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
     *
     * @param name
     * @param model
     * @return
     */
    @RequestMapping("/getURITemplate/{name}")
    public String getURITemplate(@PathVariable("name") String name, Model model) {
        User user = userService.get(name);
        model.addAttribute("user", user);
        return "user";
    }


    /**
     * 矩阵变量：
     * 多个变量，分号分隔。name=sam;mobile=123456
     * 一个变量多个值：逗号分隔。name=sam,name=eason
     * <p>
     * http://localhost:8080/user/getMatrixVariable/sam;mobile=123
     * <p>
     * 默认是关闭的，如需要使用则必须开启。且配合 URI Template Patterns 使用
     * requestMappingHandlerMapping.setRemoveSemicolonContent(false);
     * <mvc:annotation-driven enable-matrix-variables="true"/>
     *
     * @param name
     * @param model
     * @return
     */
    @RequestMapping("/getMatrixVariable/{name}")
    public String getMatrixVariable(@PathVariable String name,
                                    @MatrixVariable(required = false) String mobile,
                                    Model model) {
        System.out.println(mobile);
        User user = userService.get(name);
        model.addAttribute("user", user);
        return "user";
    }


}
